#include <webx/menu.h>

class GetUserSubMenuList : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(GetUserSubMenuList)

int GetUserSubMenuList::process()
{
	string grouplist;
	set<string> menus;
	set<MenuItem> menuset;
	set<GroupItem> groupset;

	param_string(folder);

	if (webx::GetMenuSet(menuset) < 0)
	{
		LogTrace(eERR, "get menu set failed");
		
		return simpleResponse(XG_SYSERR);
	}

	if (webx::GetGroupSet(groupset) < 0)
	{
		LogTrace(eERR, "get group set failed");
		
		return simpleResponse(XG_SYSERR);
	}

	try
	{
		checkLogin();

		grouplist = session->get("GROUPLIST");
	}
	catch(Exception e)
	{
	}

	string client = request->getHeadValue("User-Agent");
	
	stdx::tolower(client);

	if (client.find("android") == string::npos && client.find("iphone") == string::npos && client.find("ipad") == string::npos)
	{
		client = "P";
	}
	else
	{
		client = "M";
	}

	int res = 0;
	string sqlcmd;
	JsonElement arr = json.addArray("list");
	sp<DBConnect> dbconn = webx::GetDBConnect();

	if (user.length() > 0)
	{
		string dbid;
		string menurl;

		if (folder == "菜单管理")
		{
			menurl = "/menupad?folder=";
			stdx::format(sqlcmd, "SELECT FOLDER,ICON FROM T_XG_MENU WHERE (TITLE IS NULL OR TITLE='') ORDER BY POSITION ASC");
		}
		else if (folder == "我的笔记" || folder == "产品管理" || folder == "我的代码" || folder == "配置文件")
		{
			if (client == "P")
			{
				const char* tabname = "T_XG_NOTE";

				dbid = this->dbid;

				if (folder == "我的笔记")
				{
					menurl = "/notepad?name=" + stdx::EncodeURL("笔记") + "&folder=";
				}
				else if (folder == "产品管理")
				{
					menurl = "/notepad?name=" + stdx::EncodeURL("产品") + "&deficon=/res/img/note/product.png&folder=";
				}
				else if (folder == "我的代码")
				{
					menurl = "/compile/notepad?name=" + stdx::EncodeURL("代码") + "&deficon=/res/img/note/code.png&folder=";

					tabname = "T_XG_CODE";
				}
				else
				{
					menurl = "/confile/notepad?name=" + stdx::EncodeURL("文件") + "&deficon=/res/img/note/configure.png&folder=";

					tabname = "T_XG_CONF";
				}

				stdx::format(sqlcmd, "SELECT FOLDER,ICON FROM %s WHERE USER='%s' AND (TITLE IS NULL OR TITLE='') ORDER BY POSITION ASC", tabname, user.c_str());
			}
			else
			{
				JsonElement item = json["list"][res++];

				item["title"] = folder;
				item["icon"] = "/res/img/menu/note.png";
				item["url"] = "/app/workspace/pub/notelist.htm";
			}
		}

		if (dbid.length() > 0) dbconn = webx::GetDBConnect(dbid);

		if (sqlcmd.length() > 0)
		{
			sqlcmd += webx::GetLimitString(dbconn.get(), 32);

			sp<QueryResult> rs = dbconn->query(sqlcmd);

			if (!rs)
			{
				res = XG_SYSERR;
			}
			else
			{
				sp<RowData> row;

				while (row = rs->next())
				{
					JsonElement item = arr[res++];
					string title = row->getString(0);

					item["title"] = title;
					item["icon"] = row->getString(1);
					item["url"] = menurl + stdx::EncodeURL(title);
				}
			}
		}
	}
	
	GroupItem grp;
	vector<string> vec;

	if (grouplist == "system" || grouplist == "header" || grouplist == "footer")
	{
		vec.push_back(grouplist);
	}
	else
	{
		stdx::split(vec, grouplist, ",");

		vec.push_back("public");
	}

	for (auto& item : vec)
	{
		if ((grp.id = item).length() > 0)
		{
			MenuItem menu;
			vector<MenuItem> ms;
			auto it = groupset.find(grp);
			
			if (it == groupset.end()) continue;
			
			for (auto& id : it->menus)
			{
				if ((menu.id = id).length() > 0)
				{
					auto it = menuset.find(menu);
					
					if (it == menuset.end() || it->title.empty() || it->url[0] == '*') continue;

					if (app->getRouteSwitch() == 0)
					{
						string url = stdx::tolower(it->url.c_str());

						if (url.find("app/workspace/pub/routelist.htm") != string::npos) continue;

						if (url.find("app/workspace/pub/timerlist.htm") != string::npos) continue;
					}

					if ((folder == "*" || folder == it->folder) && menus.insert(it->title).second)
					{
						if (client == "M" && it->url[0] == '@') continue;

						ms.push_back(*it);
					}
				}
			}
			
			std::sort(ms.begin(), ms.end(), [](const MenuItem& a, const MenuItem& b){
				return a.position < b.position;
			});

			for (auto& m : ms)
			{
				if (client == "M" && m.icon == "/res/img/menu/addfolder.png") continue;

				JsonElement item = arr[res++];

				item["icon"] = m.icon;
				item["title"] = m.title;
				
				if (m.url[0] == '@')
				{
					item["url"] = m.url.substr(1);
				}
				else
				{
					item["url"] = m.url;
				}
				
				item["folder"] = m.folder;
			}
		}
	}

	json["user"] = user;
	json["code"] = res;
	out << json;

	return XG_OK;
}